package com.guoqing.example.config;

import com.guoqing.example.mapper.UserMapper;
import com.guoqing.example.po.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @ClassName MyRealm
 * @Description TODO
 * @Author ZhangGuoQing
 * @Date 2020/8/19/0019 19:58
 */
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserMapper userMapper;

    /**
     * 执行授权逻辑
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权");
        //获取登录用户名
        User user = (User) principalCollection.getPrimaryPrincipal();
        //添加角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        user.getRoles().forEach(role -> {
            simpleAuthorizationInfo.addRole(role.getRoleName());
            role.getResources().forEach(resource -> {
                simpleAuthorizationInfo.addStringPermission(resource.getResourceName());
            });
        });
        return simpleAuthorizationInfo;
    }

    /**
     * 执行认证逻辑
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //加这一步的目的是在Post请求的时候会先进认证，然后在到请求
        System.out.println("认证");
        if (authenticationToken.getPrincipal() == null) {
            return null;
        }
        String loginName = authenticationToken.getPrincipal().toString();
        if (StringUtils.isNotBlank(loginName)) {
//            User user = userMapper.selectUserByLoginName(loginName);
            User user = userMapper.userRoleResources(loginName);
            if (user == null) {
                return null;
            }
            String name = getName();
            System.out.println(name);
            return new SimpleAuthenticationInfo(user, user.getPwd(), name);
        }
        return null;
    }
}
